package com.example.myapplication1.publishFriendCircle;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

/**
 * Copyright (C), 2020, 重庆八进制有限公司
 *
 * @author: SuperChen
 * @last-modifier: SuperChen
 * @version: 1.0
 * @create-date: 2020/9/8 9:35
 * @last-modify-date: 2020/9/8 9:35
 * @description:
 */
public abstract class AddPictureTouchAdapter<T, VH extends RecyclerView.ViewHolder> extends ItemTouchAdapter<T, VH> {

    public static final int VIEW_TYPE_NORMAL = 0;
    public static final int VIEW_TYPE_ADD_ITEM = 1;

    private int maxCount;
    private AddPictureOnItemClickListener<T> onItemClickListener;

    public AddPictureTouchAdapter(@NonNull Context context) {
        super(context);
    }

    protected abstract void onBindViewHolder(@NonNull VH holder, int position, @Nullable T data, boolean isAddPictureItem);


    @Override
    public final void onBindViewHolder(@NonNull final VH holder, final int position) {
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onItemClickListener != null) {
                    onItemClickListener.onItemClick(holder.getItemViewType() == VIEW_TYPE_ADD_ITEM ? null : getItem(position), holder.getItemViewType() == VIEW_TYPE_ADD_ITEM);
                }
            }
        });
        onBindViewHolder(holder, position, getItem(position), holder.getItemViewType() == VIEW_TYPE_ADD_ITEM);
    }

    @Override
    public int getItemViewType(int position) {
        if (!checkIsFull()) {
            return position == getItemCount() - 1 ? VIEW_TYPE_ADD_ITEM : VIEW_TYPE_NORMAL;
        }
        return VIEW_TYPE_NORMAL;
    }

    @Override
    public int getItemCount() {
        return checkIsFull() ? maxCount : getDataCount() + 1;
    }

    @Override
    protected void notifyChanged() {
        super.notifyChanged();
        if (checkIsFull()) {
            mCannotMovePositionList = null;
        } else {
            mCannotMovePositionList = new ArrayList<>();
            mCannotMovePositionList.add(getItemCount() - 1);
        }
    }

    /**
     * 检测是否已经达到最大可选数量
     */
    protected boolean checkIsFull() {
        return getDataCount() == maxCount;
    }

    public void setMaxCount(int maxCount) {
        this.maxCount = maxCount;
    }

    public int getMaxSelectCount() {
        return maxCount;
    }

    public void setOnItemClickListener(AddPictureOnItemClickListener<T> onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public interface AddPictureOnItemClickListener<T> {
        void onItemClick(@Nullable T data, boolean isAddPictureItem);
    }
}
